package com.scx.controller.admin;

import cn.hutool.core.io.FileUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.scx.bizmq.BiMessageProducer;
import com.scx.config.RedisLimiterManager;
import com.scx.constant.ChartConstant;
import com.scx.context.BaseContext;
import com.scx.dto.*;
import com.scx.entity.Chart;
import com.scx.result.Result;
import com.scx.service.ChartService;
import com.scx.service.UserService;
import com.scx.utils.AiUtils;
import com.scx.utils.ExcelUtils;
import com.scx.vo.BiResponse;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * 帖子接口
 */
@RestController
@RequestMapping("/chart")
@Api(tags = "数据分析接口")
@Slf4j
public class ChartController {

    @Resource
    private ChartService chartService;

    @Resource
    private UserService userService;

    @Resource
    private RedisLimiterManager redisLimiterManager;

    @Resource
    private BiMessageProducer biMessageProducer;

    /**
     * 创建
     *
     * @param chartAddRequest
     * @return
     */
    @PostMapping("/add")
    public Result<Long> addChart(@RequestBody ChartAddRequest chartAddRequest) {
        Chart chart = new Chart();
        BeanUtils.copyProperties(chartAddRequest, chart);
        chart.setUserId(BaseContext.getCurrentId());
        boolean result = chartService.save(chart);
        if (!result) {
            return Result.error("创建失败");
        }
        long newChartId = chart.getId();
        return Result.success(newChartId);
    }

    /**
     * 删除
     *
     * @param id
     * @return
     */
    @PostMapping("/delete/{id}")
    public Result<Boolean> deleteChart(long id) {
        // 判断是否存在
        Chart oldChart = chartService.getById(id);
        if (oldChart == null) {
            return Result.error("图表不存在");
        }
        // 仅本人可删除
        if (!oldChart.getUserId().equals(BaseContext.getCurrentId())) {
            return Result.error("权限错误");
        }
        boolean b = chartService.removeById(id);
        return Result.success(b);
    }


    /**
     * 根据 id 获取
     *
     * @param id
     * @return
     */
    @GetMapping("/get/{id}")
    public Result<Chart> getChartById(@PathVariable long id) {
        Chart chart = chartService.getById(id);
        if (chart == null) {
            return Result.error("图表不存在");
        }
        return Result.success(chart);
    }


    /**
     * 分页获取列表（封装类）
     *
     * @param chartQueryRequest
     * @return
     */
    @PostMapping("/list/page")
    public Result<Page<Chart>> listChartByPage(@RequestBody ChartQueryRequest chartQueryRequest) {
        long current = chartQueryRequest.getCurrent();
        long size = chartQueryRequest.getSize();
        Page<Chart> chartPage = chartService.page(new Page<>(current, size),
                chartService.getQueryWrapper(chartQueryRequest));
        return Result.success(chartPage);
    }


    /**
     * 智能分析(同步实现)
     *
     * @param multipartFile
     * @param genChartByAiRequest
     * @return
     */
    @PostMapping("/gen")
    public Result<BiResponse> genChartByAi(@RequestPart("file") MultipartFile multipartFile,
                                           GenChartByAiRequest genChartByAiRequest) {

        //限流
        redisLimiterManager.doRateLimiter("ChartByAi_" + BaseContext.getCurrentId());

        String name = genChartByAiRequest.getName();
        String goal = genChartByAiRequest.getGoal();
        String chartType = genChartByAiRequest.getChartType();

        if (StringUtils.isBlank(goal)) {
            return Result.error("目标为空");
        }
        if (StringUtils.isNotBlank(name) && name.length() > 100) {
            return Result.error("名称过长");
        }

        // 校验文件
        long fileSize = multipartFile.getSize();
        String filename = multipartFile.getOriginalFilename();
        String suffix = FileUtil.getSuffix(filename);

        // 校验大小
        final long TEN_MB = 10 * 1024 * 1024L;
        if (fileSize > TEN_MB) {
            return Result.error("文件过大（大于10MB）");
        }

        // 校验格式(后缀)
        final List<String> suffixList = Arrays.asList("csv", "xlsx");
        if (!suffixList.contains(suffix)) {
            return Result.error("文件格式错误");
        }

        if (StringUtils.isNotBlank(chartType)) {
            goal += ",请使用" + chartType + "图进行分析";
        }

        /*
        分析需求：
        分析网站用户的增长情况
        原始数据：
        日期,用户数
        1号,10
        2号,20
        3号,30
        */

        StringBuilder userInput = new StringBuilder();
        userInput.append("分析需求:").append("\n").append(goal).append("\n");

        // 处理 Excel 文件
        String csv = ExcelUtils.excelTpCsv(multipartFile);
        userInput.append("原始数据:").append("\n").append(csv);

        // 调用 AI 接口
        String result = AiUtils.doChat(userInput.toString());

        if (StringUtils.isBlank(result)) {
            return Result.error("AI未得到结果");
        }
        System.out.println(result);

        String[] parts = result.split("```json\n");
        if (parts.length < 2) {
            return Result.error("AI 返回的 JSON 数据格式有误");
        }

        // 提取代码部分
        String code = parts[1].split("```")[0].trim();
        // 提取结论部分
        String conclusion = result.split("```")[2].trim();

        Chart chart = new Chart();
        chart.setName(name);
        chart.setGoal(goal);
        chart.setChartData(csv);
        chart.setChartType(chartType);
        chart.setGenChart(code);
        chart.setGenResult(conclusion);
        chart.setStatus(ChartConstant.SUCCEED);
        chart.setUserId(BaseContext.getCurrentId());

        boolean save = chartService.save(chart);
        if (!save) {
            return Result.error("图表保存失败");
        }

        BiResponse biResponse = new BiResponse();
        biResponse.setGenChart(code);
        biResponse.setGenResult(conclusion);
        biResponse.setChartId(chart.getId());
        return Result.success(biResponse);
    }

    /**
     * 智能分析（异步实现）,使用RabbitMQ
     *
     * @param multipartFile
     * @param genChartByAiRequest
     * @return
     */
    @PostMapping("/gen/async")
    public Result<BiResponse> genChartByAiAsync(@RequestPart("file") MultipartFile multipartFile,
                                                GenChartByAiRequest genChartByAiRequest) {

        // 限流
        redisLimiterManager.doRateLimiter("ChartByAi_" + BaseContext.getCurrentId());

        String name = genChartByAiRequest.getName();
        String goal = genChartByAiRequest.getGoal();
        String chartType = genChartByAiRequest.getChartType();

        if (StringUtils.isBlank(goal)) {
            return Result.error("目标为空");
        }
        if (StringUtils.isNotBlank(name) && name.length() > 100) {
            return Result.error("名称过长");
        }

        // 校验文件
        long fileSize = multipartFile.getSize();
        String filename = multipartFile.getOriginalFilename();
        String suffix = FileUtil.getSuffix(filename);

        // 校验大小
        final long TEN_MB = 10 * 1024 * 1024L;
        if (fileSize > TEN_MB) {
            return Result.error("文件过大（大于10MB）");
        }

        // 校验格式(后缀)
        final List<String> suffixList = Arrays.asList("csv", "xlsx", "xls");
        if (!suffixList.contains(suffix)) {
            return Result.error("文件格式错误");
        }

        if (StringUtils.isNotBlank(chartType)) {
            goal += ",请使用" + chartType + "图进行分析";
        }

        // 解析数据
        StringBuilder userInput = new StringBuilder();
        userInput.append("分析需求:").append("\n").append(goal).append("\n");

        // 处理 Excel 文件
        String csv = ExcelUtils.excelTpCsv(multipartFile);
        userInput.append("原始数据:").append("\n").append(csv);

        // 添加到数据库
        Chart chart = new Chart();
        chart.setName(name);
        chart.setGoal(goal);
        chart.setChartData(csv);
        chart.setChartType(chartType);
        chart.setStatus(ChartConstant.WAIT);
        chart.setUserId(BaseContext.getCurrentId());

        boolean save = chartService.save(chart);
        if (!save) {
            return Result.error("图表保存失败");
        }

        // 发送消息到 RabbitMQ，异步调用 AI 接口
        Map<String, Object> map = new HashMap<>();
        map.put("chartId", chart.getId());
        map.put("userInput", userInput.toString());
        biMessageProducer.sendMessage(map);

        BiResponse biResponse = new BiResponse();
        biResponse.setChartId(chart.getId());
        return Result.success(biResponse);
    }

}
